<template>
  <div class="xtx-form">
    <div class="user-info">
      <img v-if="avatar" :src="avatar" alt="" />
      <img v-else src="@/assets/images/load.gif" alt="" />
      <p>Hi，{{ nickname }} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <input v-model="form.mobile" class="input" type="text" placeholder="绑定的手机号" />
      </div>
      <div class="error"></div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <input v-model="form.code" class="input" type="text" placeholder="短信验证码" />
        <span @click="sendCode()" class="code">{{ countTime === 0 ? '发送验证码' : `${countTime}秒后尝试` }}</span>
      </div>
      <div class="error"></div>
    </div>
    <a href="javascript:;" @click="submit()" class="submit">立即绑定</a>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue-demi'
import { useCountDown } from '@/hooks'
import { reqUserQQBindCode, reqUserQQBindLogin } from '@/api/user'
import { message } from '@/components/Message'
import { useStore } from '@/store'
import { useRouter } from 'vue-router'
const { user, cart } = useStore()
const router = useRouter()

const props = defineProps({
  unionId: {
    type: String
  }
})
const avatar = ref('')
const nickname = ref('')
if (QC.Login.check()) {
  QC.api('get_user_info').success((res: any) => {
    avatar.value = res.data.figureurl_1
    nickname.value = res.data.nickname
  })
}

const form = reactive({
  mobile: '',
  code: ''
})
// 调用倒计时函数 countTime 倒计时数字 , start 启动倒计时的函数
const { countTime, start } = useCountDown(60)
const sendCode = async () => {
  // 先校验手机号码，有错误退出函数并提示用户
  if (!/^1[3-9]\d{9}$/.test(form.mobile)) return message({ text: '手机号码格式错误' })
  // 💥💥 发送手机验证码 - 注意这里调用的是新的验证码接口
  await reqUserQQBindCode(form.mobile)
  message({ type: 'success', text: '验证码发送成功' })
  // 发送验证码成功就启动倒计时
  start()
}

const submit = async () => {
  // Win + V 剪贴板
  const { result } = await reqUserQQBindLogin({
    unionId: props.unionId,
    ...form
  })
  // 1. result 存储着用户的信息，可以直接存储到 Vuex 仓库中
  await user.setProfile(result)
  // 🔔 合并购物车
  await cart.mergeLocalCart()
  // 2. 跳转页面
  router.push('/')
  // 3. 提示用户
  message({ type: 'success', text: 'QQ绑定成功' })
}
</script>

<style scoped lang="scss">

.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
